﻿using System;
using System.Diagnostics;
using System.IO;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using Ursa.Controls;

namespace STT_Test_Plus.ViewModels;

public class MicrosoftDemoViewModel:ObservableObject
{
    public RelayCommand OpenKeyboardCmd { get; }

    public MicrosoftDemoViewModel()
    {
        OpenKeyboardCmd = new RelayCommand(OpenKeyboard);
    }

    private async void OpenKeyboard()
    {
        if (!OpenWindowsTouchKeybord(out var errMsg))
        {
            await MessageBox.ShowAsync(errMsg, "错误", MessageBoxIcon.Error, MessageBoxButton.OK);
        }
    }
    
    /// <summary>
    /// 打开Windows触摸键盘
    /// </summary>
    public static bool OpenWindowsTouchKeybord(out string errMsg)
    {
        try
        {
            var processes = Process.GetProcessesByName(Path.GetFileNameWithoutExtension("TabTip"));
            foreach (var p in processes)
            {
                p.Kill();
            }

            var commonFilesPath = Environment.GetFolderPath(Environment.SpecialFolder.CommonProgramFiles);
            //程序集目标平台为X86时，获取到的是x86的Program Files，但TabTip.exe始终在Program Files目录下
            if (commonFilesPath.Contains("Program Files (x86)"))
            {
                commonFilesPath = commonFilesPath.Replace("Program Files (x86)", "Program Files");
            }

            var tabTipPath = Path.Combine(commonFilesPath, @"microsoft shared\ink\TabTip.exe");
            if (File.Exists(tabTipPath))
            {
                ProcessStartInfo psi = new ProcessStartInfo
                {
                    FileName = tabTipPath,
                    UseShellExecute = true,
                    CreateNoWindow = true
                };
                Process.Start(psi);
                errMsg = "";
                return true;
            }

            errMsg = $"{tabTipPath}不存在";
            return false;
        }
        catch (Exception e)
        {
            errMsg = e.Message;
            return false;
        }
    }
}